package org.microser.gataway.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ErrorFilter extends SendErrorFilter {

    @Override
    public Object run() {
        Map map = new HashMap();
        try{
            RequestContext ctx = RequestContext.getCurrentContext();
            //获取错误message
            String msg = String.valueOf(ctx.getRequest().getAttribute("msg"));
            String code = String.valueOf(ctx.getRequest().getAttribute("code"));
            //发送错误的源头
            ExceptionHolder exception = findZuulException(ctx.getThrowable());
            System.out.println("错误信息:"+ exception.getErrorCause());

            if(StringUtils.isEmpty(code)){
                map.put("code",ctx.getResponseStatusCode());
            }else{
                map.put("code",code);
            }
            map.put("msg",msg);
            HttpServletResponse response = ctx.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.getOutputStream().write(JSONObject.toJSONString(map).getBytes("utf-8"));
        }catch (Exception ex) {
            ex.printStackTrace();
            ReflectionUtils.rethrowRuntimeException(ex);
        }
        return map;
    }

}
